# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/4/2 10:27
# @Author  : qiaoc
# @File    : AuditCuring.py
# @Desc    :

import os
from ocr.Ocr import *
from dao.PyMysql import *
from affix import AffixUtils

# 固化类型
def audit_curing(bill_number, floder_path, address_name, pricess, type):
    """ success == 0 成功通过稽核；\r\n
        success == 1 转人工\r\n
        success == 2 稽核不通过
      """
    audit_refused_type = {}  # 审核不通过类型
    audit_result_operate = [0, 0]  # 转人工、不通过
    audit_list = []  # 稽核结果集，需存库
    result = {'success': 0, 'message': '通过'}
    # 第二步：查询数据库固化页面信息表中的数据
    try:
        fixed_electric_charge_tablename = 'fixed_electric_charge'  # 固化单据电费信息数据库表
        fixed_electric_charge_sql = """SELECT * FROM """ + fixed_electric_charge_tablename + """ WHERE fixed_code='""" + str(
            bill_number) + """'"""
        fixed_electric_charge_data = PyMysql().get_db_data(fixed_electric_charge_sql)
        page_power_type = fixed_electric_charge_data[0]['power_type']
        if page_power_type and '转供电' in str(page_power_type):
            audit_result_operate[0] = 1  # 转人工
            audit_list.append([str(bill_number), '供电类型判断', page_power_type, '', '0', 'RPA', '【供电类型】是“转供电”直接转人工不作稽核', '', '11', ''])
        else:
            all_file = os.listdir(floder_path)
            # all_file.sort()
            AffixUtils.file_classification(floder_path)
            all_ocr_attachment, rar_file= AffixUtils.get_curing_ocr_attachment(floder_path)
            # 第一步：印章识别
            stam_f = 0
            stam_content = ''
            if len(all_ocr_attachment) == 0:
                audit_result_operate[0] = 1  # 转人工
                audit_list.append([str(bill_number), '电力明细印章', '电力或供电', stam_content, '0', 'RPA', '找不到附件，请注意命名规范', '', '14', ''])
            else:
                for stamp_img in all_ocr_attachment:
                    stamp_re = Ocr().get_curing_ocr_attachment(stamp_img[1], ['电力', '供电'])
                    if isinstance(stamp_re['data'], list):
                        stamp_re['data'] = stamp_re['data'][0]
                    if stam_content:
                        stam_content = stam_content + ',' + stamp_re['data']
                    else:
                        stam_content = stamp_re['data']
                    if stamp_re['success'] == 0:
                        stam_f = 1
                if stam_f == 0:
                    audit_result_operate[0] = 1  # 转人工
                    audit_list.append([str(bill_number), '电力明细印章', '电力或供电', stam_content, '0', 'RPA', '未检测到指定印章', '', '14', ''])
                else:
                    audit_list.append([str(bill_number), '电力明细印章', '电力或供电', stam_content, '1', 'RPA', '合格', '', '14', ''])
                # 第四步：查询数据库固化OCR识别信息表中是否已经有对应数据
                # site_name = electric_charge['site_name'] # 页面的固化信息名称

                ocr_su_sql = """SELECT * FROM """ + PyMysql().bill_table_name + """ WHERE affixx_name='""" + str(all_ocr_attachment[0][0]) + """'"""
                # ocr_su_sql = """SELECT * FROM """ + PyMysql().bill_table_name + """ WHERE bill_number='""" + str(
                #     bill_number) + """' AND site_name='""" + str(address_name) + """'"""
                any_ocr_data = PyMysql().get_db_data(ocr_su_sql)
                if any_ocr_data and len(any_ocr_data) > 0:
                    # 找到了，则查询所有识别数据，并做稽核
                    pass
                else:
                    # 找不到，则OCR所有的图片，存库
                    try:
                        Ocr().ocr_img_list(all_ocr_attachment, bill_number, type,1)
                    except Exception as e:
                        pass
                prices_list = str(pricess).split(";")
                for pri_idx in range(len(prices_list)):
                    attach_name = ('附件' + str(pri_idx+1))
                    select_data = None
                    attach_exits = False
                    for attach in all_ocr_attachment:
                        if attach_name in attach[0]:
                            attach_exits = True
                            ocr_curing_sql = """SELECT * FROM """ + PyMysql().bill_table_name + """ WHERE  affixx_name='""" + attach[0] + """'"""
                            select_data = PyMysql().get_db_data(ocr_curing_sql)
                    if attach_exits:
                        # 附件找到了
                        if not select_data:
                            # 没有附件数据
                            audit_result_operate[0] = 1  # 转人工
                            audit_list.append([str(bill_number), '普通表单价' + str(pri_idx+1), str(prices_list[pri_idx]), '', '0', 'RPA', attach_name + '中未识别出数据', '', '14', ''])
                        else:
                            # 有数据
                            ele_price = None
                            for da in select_data:
                                site_name = da['site_name']
                                if str(address_name).strip() in str(site_name).strip() or str(site_name).strip() in str(address_name).strip():
                                    ele_price = da['ele_price']
                                    if ele_price and is_number(ele_price):
                                        if float(ele_price) == float(prices_list[pri_idx]):
                                            audit_list.append([str(bill_number), '普通表单价' + str(pri_idx+1), str(prices_list[pri_idx]), str(ele_price), '1', 'RPA', '合格', '', '12', ''])
                                        else:
                                            audit_result_operate[1] = 1  # 不通过
                                            audit_refused_type['信息与明细不符'] = 0
                                            audit_list.append([str(bill_number), '普通表单价' + str(pri_idx+1), str(prices_list[pri_idx]), str(ele_price),
                                                 '0', 'RPA', '普通表单价信息与附件不一致', '', '14', ''])
                            if not ele_price:
                                audit_result_operate[0] = 1  # 转人工
                                audit_list.append([str(bill_number), '普通表单价' + str(pri_idx+1), str(prices_list[pri_idx]), '', '0', 'RPA', attach_name + '中未识别出数据', '', '14', ''])
                    else:
                        # 附件没有找到
                        audit_result_operate[0] = 1  # 转人工
                        audit_list.append([str(bill_number), '普通表单价' + str(pri_idx+1), str(prices_list[pri_idx]), '', '0', 'RPA', attach_name+'不存在', '', '14', ''])
            # 第五步：查询所有附件中OCR识别结果的对应“固化信息名称”数据
            # all_ocr_curing_data = []
            # for attach in all_file:
            #     ocr_curing_sql = """SELECT * FROM """ + PyMysql().bill_table_name + """ WHERE  affixx_name='""" + attach + """'"""
            #     dbdata = PyMysql().get_db_data(ocr_curing_sql)
            #     if dbdata and len(dbdata) > 0:
            #         all_ocr_curing_data.append(dbdata)
            #
            # if len(all_ocr_curing_data) > 0:
            #     ocr_pp = all_ocr_curing_data[0]
            #     add_audit_re = False
            #     for o in ocr_pp:
            #         if o['uname'] and address_name in o['uname']:
            #             add_audit_re = True
            #             # 第六步：按顺序比较电价
            #             prices_list = str(pricess).split(";")
            #             for pri_idx in range(len(prices_list)):
            #                 o_price = o['ele_price']
            #                 # ocr_p = all_ocr_curing_data[0]
            #                 if not o_price or len(ocr_pp) == 0:
            #                     audit_result_operate[0] = 1  # 转人工
            #                     audit_list.append(
            #                         [str(bill_number), '普通表单价' + str(pri_idx), str(prices_list[pri_idx]), '', '0', 'RPA',
            #                          'OCR识别此站址电价数据为空', '', '14', ''])
            #                 ocr_curing_price = str(o_price).replace('元', '').strip().split(';')
            #                 if ocr_curing_price[pri_idx] not in prices_list:
            #                     audit_result_operate[1] = 1  # 不通过
            #                     audit_refused_type['信息与明细不符'] = 0
            #                     audit_list.append(
            #                         [str(bill_number), '普通表单价', str(prices_list[pri_idx]), str(ocr_curing_price), '0', 'RPA',
            #                          '普通表单价信息与附件不一致', '', '14', ''])
            #                 else:
            #                     audit_list.append([str(bill_number), '普通表单价', str(prices_list[pri_idx]), str(ocr_curing_price), '1', 'RPA', '合格', '', '14', ''])
            #     if not add_audit_re:
            #         audit_result_operate[0] = 1  # 转人工
            #         audit_list.append([str(bill_number), '普通表单价', address_name, '', '0', 'RPA', '附件中未找到此站址名称', '', '14', ''])
            # else:
            #     audit_result_operate[0] = 1  # 转人工
            #     audit_list.append([str(bill_number), '普通表单价', address_name, '', '0', 'RPA', 'OCR识别此站址数据为空', '', '14', ''])
        # 存储稽核信息到数据库中
        # try:
        PyMysql().insert_data(PyMysql().nf_audit_point_tablename, PyMysql().nf_audit_point_table_key, audit_list)
        # except Exception as e:
        #     pass
        result['message'] = 0
        # try:
        audit_status = '通过'
        is_artificial = 1
        if audit_result_operate[0] == 1:
            audit_status = '审核中'
            is_artificial = 0
            result['success'] = 1
        elif audit_result_operate[1] == 1:
            audit_status = '不通过'
            result['success'] = 2
            # 不通过类型插入数据库动作
            PyMysql().ergodic_Noresult_audit_list(audit_list)
        if audit_status == '通过':
            PyMysql().update_nf_audit_info(str(bill_number), '通过', '')
        audit_refused_type_str = ''
        for t in audit_refused_type:
            if audit_refused_type_str:
                audit_refused_type_str = audit_refused_type_str + ',' + str(t)
            else:
                audit_refused_type_str = str(t)
        audit_remark = ''  # 审核意见
        for po in audit_list:
            if audit_remark:
                if "合格" in str(po[6]):
                    continue
                audit_remark = audit_remark + ',' + str(po[6])
            else:
                if "合格" in str(po[6]):
                    continue
                audit_remark = str(po[6])
        result['message'] = audit_remark
        save_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        type_ele = '电费固化信息审核'
        # PyMysql().insert_data(PyMysql().sys_audit_info_tablename, sys_audit_info_table_key,
        #             [[bill_number, audit_status, audit_refused_type_str, audit_remark, is_artificial, save_time]])
        update_sql = """UPDATE """ + PyMysql().sys_audit_info_tablename + """ SET audit_status='""" + \
                     str(audit_status) + """',audit_refused_type='""" + str(
            audit_refused_type_str) + """',audit_rd_type='""" + str(audit_remark) + """',is_artificial='""" + \
                     str(is_artificial) + """',save_time='""" + str(
            save_time) + """' WHERE payment_code='""" + str(bill_number) + """' AND document_type='""" + str(
            type_ele) + """'"""
        PyMysql().execute_sql(update_sql)
        # except Exception as e:
        #     pass
    except Exception as e:
        # print(e,e.__traceback__.tb_lineno)
        result['success'] = 1
        audit_result_operate[0] = 1  # 转人工
        audit_list.append([str(bill_number), '普通表单价', address_name, '', '0', 'RPA', 'OCR识别此站址数据为空', '', '14', ''])
        audit_list.append([str(bill_number), '电力明细印章', address_name, '', '0', 'RPA', '未检测到指定印章', '', '14', ''])
        result['message'] = 'RPA处理异常'
    return result



def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        return False
